﻿using System;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using battlenet.wow.rt.sdk.configuration;
using battlenet.wow.rt.sdk.data.serialization;
using Newtonsoft.Json;

namespace battlenet.wow.rt.sdk.Data.Proxy
{
    internal abstract class BattlenetApiProxy<T> // TODO: remove this -- deserialization should happen outside of the proxy
        where T : class
    {
        
        private readonly Uri _hostBaseAddress = new Uri("https://us.api.battle.net");

        /// <summary>
        /// Requests the data asynchronous.
        /// </summary>
        /// <param name="resource">The resource.</param>
        /// <returns></returns>
        public async Task<T> RequestDataAsync(string resource)
        {
            AddApiKey(ref resource);
            var response = await HttpRequestHelper.GetHttpResponse(new Uri(_hostBaseAddress, resource));
            var body = response.Item2;
            Debug.WriteLine(body);

            if (string.IsNullOrEmpty(body)) return null;

            var t = JsonConvert.DeserializeObject<T>(body, new JsonDateTimeConverter());
            return t;
        }

        private static void AddApiKey(ref string resource)
        {
            if (string.IsNullOrEmpty(BnSystem.ApiKey)) return;

            var prefix = resource.IndexOf("?", StringComparison.Ordinal) > -1 ? "&" : "?";
            resource += string.Format("{0}apikey={1}", prefix, BnSystem.ApiKey);
        }

        private async static Task<string> GetJsonResponseAsync(Uri url)
        {
            var client = new HttpClient();
            var response = await client.GetAsync(url);
            return await response.Content.ReadAsStringAsync();
        }
    }

    internal class HttpRequestHelper
    {
        /// <summary>
        /// Gets the HTTP response body.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <returns></returns>
        public async static Task<Tuple<HttpStatusCode, string>> GetHttpResponse(string url)
        {
            return await GetHttpResponse(new Uri(url));
        }

        /// <summary>
        /// Gets the HTTP response body.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <returns></returns>
        public async static Task<Tuple<HttpStatusCode, string>> GetHttpResponse(Uri uri)
        {
            var client = new HttpClient();
            var response = await client.GetAsync(uri);
            return new Tuple<HttpStatusCode, string>(response.StatusCode, await response.Content.ReadAsStringAsync());
        }
    }
}
